package com.ljh.localmusic.foundation.di

import android.content.Context
import androidx.annotation.OptIn
import androidx.media3.common.AudioAttributes
import androidx.media3.common.C
import androidx.media3.common.Player
import androidx.media3.common.util.UnstableApi
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.exoplayer.trackselection.DefaultTrackSelector
import androidx.media3.session.MediaSession
import com.ljh.localmusic.data.local.ContentResolverHelper
import com.ljh.localmusic.data.remote.AuthInterceptor
import com.ljh.localmusic.data.remote.BaseApi
import com.ljh.localmusic.data.remote.ImageApi
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import javax.inject.Singleton

/**
 * author：LJH on 2025/8/15 16:28
 *
 */
@Module
@InstallIn(SingletonComponent::class)
class RepositoryModule {

    private val logInterceptor: HttpLoggingInterceptor = HttpLoggingInterceptor().apply {
        level = HttpLoggingInterceptor.Level.BODY
    }

    private val authInterceptor = AuthInterceptor()

    val client = OkHttpClient.Builder()
        //.dns(CustomDns())  //自定义 DNS
        //可根据需要开启超时
        //.connectTimeout(30, TimeUnit.SECONDS)
        //.readTimeout(30, TimeUnit.SECONDS)
        //.writeTimeout(30, TimeUnit.SECONDS)
        //.addInterceptor(ChangeBaseUrlInterceptor()) // BaseUrl 拦截器
        // 可选日志拦截器
        .addInterceptor(logInterceptor) // 可选日志拦截器
        .addInterceptor(authInterceptor) // 请求头
        .retryOnConnectionFailure(true)
        .build()

    @Singleton
    @Provides
    fun providerImageGenerateApi(): ImageApi {
        return Retrofit.Builder()
            .addConverterFactory(GsonConverterFactory.create())
            .baseUrl(BaseApi.BASE_URL)
            .client(client)
            .build()
            .create(ImageApi::class.java)
    }

    @Provides
    fun provideContentResolverHelper(
        @ApplicationContext context: Context
    ): ContentResolverHelper = ContentResolverHelper(context)


    @OptIn(UnstableApi::class)
    @Provides
    @Singleton
    fun provideExoPlayer(
        @ApplicationContext context: Context
    ): Player{
        return  ExoPlayer.Builder(context)
            .setSeekBackIncrementMs(10*1000)
            .setSeekForwardIncrementMs(10*1000)
            .setAudioAttributes(AudioAttributes.Builder()
                .setContentType(C.AUDIO_CONTENT_TYPE_MUSIC)
                .setUsage(C.USAGE_MEDIA)
                .build(), true)
            .setHandleAudioBecomingNoisy(true)
            .setTrackSelector(DefaultTrackSelector(context))
            .build()
    }

    @OptIn(UnstableApi::class)
    @Provides
    @Singleton
    fun provideMediaSession(
        @ApplicationContext context: Context,
        player: Player
    ): MediaSession{
        // 1. 创建自定义 Callback，关联 Player
//        val sessionCallback = CustomMediaSessionCallback(player, context)

        // 2. 构建 MediaSession 实例
        val mediaSession = MediaSession.Builder(
            context, // 传入 Application Context，避免内存泄漏
            player   // 关联 ExoPlayer 实例
        )
//            .setCallback(sessionCallback) // 设置事件回调
//            .setSessionName("LocalMusicSession") // 会话名称（自定义，如“本地音乐会话”）
            .build()

        // 3. 可选配置：限制单会话（避免多控制器同时控制）
//        mediaSession.isSingleSession = true

        // 4. 可选配置：支持媒体通知（需配合 MediaSessionService，见下文扩展）
        // mediaSession.setMediaNotificationProvider(...)

        return mediaSession
    }

//    @OptIn(UnstableApi::class)
//    @Provides
//    @Singleton
//    fun provideMusicNotificationManager(
//        @ApplicationContext context: Context,
//        player: Player
//    ):MusicNotificationManager{
//
//    }
}